import React from 'react';
import get from 'lodash/get';
import PropTypes from 'prop-types';
import { stripesConnect } from '@folio/stripes/core';

import { FormattedMessage } from 'react-intl';
import { StripesConnectedSource } from '@folio/stripes/smart-components';
import {
  MultiColumnList
} from '@folio/stripes/components';

import SearchForm from '../../components/party-log/search-form';
import defaultParser from '../../util/DateParser';

class List extends React.Component {
  static manifest = Object.freeze({

    logQuery: { initialValue: '' },
    resultCount: { initialValue: 20 },
    partyLogGroupRecords: {
      type: 'okapi',
      path: 'party/log',
      recordsRequired: '%{resultCount}',
      perRequest: 20,
      limitParam: 'limit',
      records: 'partyLogGroup',
      GET: {
        params: {
          // eslint-disable-next-line no-template-curly-in-string
          query: '( isDel = 0 ${logQuery} ) sortby metadata.createdDate/sort.descending '
        }
      }
      // offsetParam: 'pageNum'
    }
  });

  static propTypes = {
    stripes: PropTypes.shape({
      logger: PropTypes.object
    }).isRequired,
    resources: PropTypes.object,
    mutator: PropTypes.shape({
      getDataList: PropTypes.shape({
        GET: PropTypes.func.isRequired
      }),

      logQuery: PropTypes.string
    }).isRequired,
    dictionary: PropTypes.object
  };

  constructor(props) {
    super(props);
    this.logger = props.stripes.logger;
    this.log = this.logger.log.bind(this.logger);
    this.state = {
      searchForm: {
        jsonb: { name: '' }
      }
    };
  }

  componentDidMount() {
    this.source = new StripesConnectedSource(this.props, this.logger);
    // this.getDataList();
  }

  componentDidUpdate() {
    this.source.update(this.props, 'partyLogGroupRecords');
  }

  componentWillUnmount() {
    const { mutator } = this.props;
    mutator.logQuery.replace('');
  }

  moreData = () => {
    if (this.source) {
      this.source.fetchMore(20);
    }
  };

  search = ({ requestPreferences, creds, ...formData }) => {
    const { mutator } = this.props;

    this.setState({ searchForm: formData });
    let query = '';
    if (!!formData && !!formData.username) {
      query += `and username == "*${formData.username}*" `;
    }
    if (!!formData && !!formData.describe) {
      query += `and describe == "*${formData.describe}*" `;
    }
    if (!!formData && !!formData.type) {
      query += `and type == ${formData.type} `;
    }
    mutator.logQuery.replace(query);
    if (this.source) {
      this.source.update(this.props);
    }
  };

  cleanSearch = () => {
    const { mutator } = this.props;
    this.setState({
      searchForm: {
        username: '',
        describe: '',
        type: ''
      }
    });
    mutator.logQuery.replace('');
    if (this.source) {
      this.source.update(this.props, 'partyLogGroupRecords');
    }
  };

  render() {
    const dictionary = {
      type:[
        { id: '', name: 'none', desc: 'ui-party.systemLog.data.type.empty' },
        { id: 0, name: 'enrollSuccess', desc: 'ui-party.systemLog.data.type.error' },
        { id: 1, name: 'signInSuccess', desc: 'ui-party.systemLog.data.type.record' },
        { id: 2, name: 'auditPass', desc: 'ui-party.systemLog.data.type.add' },
        { id: 3, name: 'auditReject', desc: 'ui-party.systemLog.data.type.modify' },
        { id: 4, name: 'auditReject', desc: 'ui-party.systemLog.data.type.delete' }
      ]
    };
    const { resources } = this.props;
    if (this.source) {
      this.source.update(this.props, 'partyLogGroupRecords');
    }
    const totalCount = this.source ? this.source.totalCount() : 0;

    const dataList = get(resources, 'partyLogGroupRecords.records', []);

    const resultsFormatter = {
      type: item => {
        const type = (dictionary.type || {}).find(t => t.id === item.type);
        return (
          <FormattedMessage id={(type || {}).desc || 'ui-party.empty'} />
        );
      },
      username: item => `${item.username}`,
      ip: item => `${item.ip}`,
      describe: item => `${item.describe}`,
      createDate: item => {
        if (item.metadata) {
          return defaultParser(
            item.metadata.createdDate,
            'Asia/Shanghai',
            'YYYY-MM-DD HH:mm'
          );
        } else {
          return '';
        }
      }
    };
    return (
      <div style={{ width:'800px', height:'700px' }}>
        <SearchForm
          onSubmit={this.search}
          initialValues={this.state.searchForm}
          cleanSearch={this.cleanSearch}
          dictionary={dictionary}
          {...this.props}
        />
        <MultiColumnList
          height={700}
          width={'820px'}
          isEmptyMessage={<FormattedMessage id="ui-party.empty.list" />} // 空数据提示
          // pagingType="click"
          totalCount={totalCount}
          virtualize
          contentData={dataList}
          onNeedMoreData={this.moreData}
          formatter={resultsFormatter}
          visibleColumns={['type', 'username', 'ip', 'describe', 'createDate']}
          columnMapping={{
            type: <FormattedMessage id="ui-party.loans.columns.systemLog.type" />,
            username: <FormattedMessage id="ui-party.loans.columns.systemLog.username" />,
            ip: <FormattedMessage id="ui-party.loans.columns.systemLog.ip" />,
            describe: <FormattedMessage id="ui-party.loans.columns.systemLog.describe" />,
            createDate: (
              <FormattedMessage id="ui-party.createDate" />
            )
          }}
          columnWidths={{
            type: '100px',
            username: '160px',
            ip: '100px',
            describe: '290px',
            createDate: '150px'
          }}
        />
      </div>
    );
  }
}
export default stripesConnect(List);
